<?php
namespace app\common\service;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class Jwtoken{

    const SECRET = 'itScrNjsZfEaN+aEjn9DtIWh17XskW0EGEmvUseW$E$YN$X8rAlBuomEHCjS0$iwJlwgj0Z9AJ6z5UToEv4kMad7BZ_y$D@YqjhNYQJ_jAxuHA$A3G3oBKS9kfXAWbQxBX2VlD_4QUR@dS$lLB1y9+CnwIu21n';
    const ISSS = 'arab-alabo';
    const AUD = 'www.arab-alabo.com';
    public function __construct(){
    }

    public function GenerateToken($uid=0, $sid=0, $pid=0,$val=null){
        $currentTime = time();
        $data = array(
            "iss" => self::ISSS, 
            "aud" => self::AUD, 
            "iat" => $currentTime,
            "nbf" => $currentTime,
            "exp" => $currentTime + 86400,
            "data" => ['uid' => $uid, 'sid'=>$sid, 'pid'=>$pid, 'value'=>$val]
        );
        $token = JWT::encode($data, self::SECRET, "HS256");
        return $token;
    }

    public function ChekToken($token)
    {
        $status=array("code"=>2);
        try {
            JWT::$leeway = 60;//当前时间减去60，把时间留点余地
            $decoded = JWT::decode($token,new Key(self::SECRET,'HS256')); //HS256方式，这里要和签发的时候对应
            $arr = (array)$decoded;
            $res['code']=1;
            $res['data']=$arr['data'];
            return $res;

        } catch(\Firebase\JWT\SignatureInvalidException $e) { //签名不正确
            $status['msg']="签名不正确";
            return $status;
        }catch(\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用
            $status['msg']="token失效";
            return $status;
        }catch(\Firebase\JWT\ExpiredException $e) { // token过期
            $status['msg']="token失效";
            return $status;
        }catch(\Exception $e) { //其他错误
            $status['msg']="未知错误";
            return $status;
        }
    }

}
